export default {
	state:{
		shopCar:localStorage.getItem('shopCar') ? JSON.parse(localStorage.getItem('shopCar')):{
			totalCount:0,
			carItem:[
				
			]
		}
	},
	mutations:{
		addToShopCar(state,shopItem){
			state.shopCar.totalCount += shopItem.count;
			var hasSame = false;
			state.shopCar.carItem.forEach(element => {
				if(element.productId === shopItem.productId)
				{
					element.count += shopItem.count;
					hasSame = true;
					return
				}
			});
			if(!hasSame)
			{
				state.shopCar.carItem.push(shopItem)
			}
			localStorage.setItem('shopCar',JSON.stringify(state.shopCar))
		},
		changeProductCount(state,product){
			state.shopCar.carItem.forEach(element=>{
				if(element.productId === product.productId)
				{
					state.shopCar.totalCount += (product.count-element.count)
					console.log(product.count+"   "+element.count)
					element.count = product.count
					localStorage.setItem('shopCar',JSON.stringify(state.shopCar))
				}
			})
		},
		deleteFromCar(state,productId)
		{
			console.log(state.shopCar.carItem)
			for(var i = 0; i < state.shopCar.carItem.length; i++)
			{
				console.log(123)
				if(state.shopCar.carItem[i].productId == productId)
				{
					console.log('aaa')
					state.shopCar.totalCount -= state.shopCar.carItem[i].count
					state.shopCar.carItem.splice(i,1);
					localStorage.setItem('shopCar',JSON.stringify(state.shopCar))
				}
			}
		}
	},
	getters:{
		getShopCarTotalCount(state){
			return state.shopCar.totalCount;
		}
	}
}